package com.thinkin.jdbc.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.Collection;

/**
 * 
 * @author cyt
 * 
 */
public class DataUtil {

	public static Collection getDatas(Collection result, ResultSet rs,
			Class clazz) {
		try {
			while (rs.next()) {
				Object vo = clazz.newInstance();
				Field[] fields = clazz.getDeclaredFields();
				// Field[] superFields =
				// clazz.getSuperclass().getDeclaredFields();
				// Field[] allFields = addFields(superFields, fields);
				for (Field field : fields) {
					String setterMethodName = getSetterMethodName(field
							.getName());
					Method setterMethod = clazz.getMethod(setterMethodName,
							field.getType());
					invokeMethod(rs, field, vo, setterMethod);
				}
				result.add(vo);
			}
			rs.close();
		} catch (Exception e) {
			e.printStackTrace();
			// throw new DataException(e.getMessage());
		}
		return result;
	}

	public static Object getData(ResultSet rs, Class clazz) {
		Object vo = null;
		try {

			while (rs.next()) {
				vo = clazz.newInstance();
				Field[] fields = clazz.getDeclaredFields();
				// Field[] superFields =
				// clazz.getSuperclass().getDeclaredFields();
				// Field[] allFields = addFields(superFields, fields);
				for (Field field : fields) {
					String setterMethodName = getSetterMethodName(field
							.getName());
					Method setterMethod = clazz.getMethod(setterMethodName,
							field.getType());
					invokeMethod(rs, field, vo, setterMethod);
				}

			}
			rs.close();
		} catch (Exception e) {
			e.printStackTrace();
			// throw new DataException(e.getMessage());
		}
		return vo;
	}

	// 执行一个方法, 从ResultSet中获取一个字段的数据, 调用vo的setter方法
	private static void invokeMethod(ResultSet rs, Field field, Object vo,
			Method setterMethod) {
		try {
			String value = rs.getString(field.getName());
			setterMethod.invoke(vo, value);
		} catch (Exception e) { // 忽略异常

		}
	}

	// 根据属性名获得setter方法的方法名
	private static String getSetterMethodName(String fieldName) {
		String begin = fieldName.substring(0, 1).toUpperCase();
		String end = fieldName.substring(1, fieldName.length());
		String methodName = "set" + begin + end;
		return methodName;
	}
}